package com.eptok.yspay.opensdkjava.util;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.Feature;
import com.eptok.yspay.opensdkjava.common.Constants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.*;

/**
 * @Author YIFan
 * @Date 2022/4/6 14:08
 * @Version 1.0
 * @DESC //TODO
 */
public class SignCheckUtil {

    private static final Logger log = LoggerFactory.getLogger(SignCheckUtil.class);

    public static String sign(String type, String pwd, String filePath, Map<String, String> params) throws Exception {
        if (!Arrays.asList("RSA", "SM").contains(type)) throw new Exception("sign_type 类型错误 只能 RSA SM");

        String sign = null;
        if (Constants.YSF_SIGN_TYPE_RSA.equals(type)) {
            // rsa
            sign = YsOnlineSignUtils.sign(params, pwd, filePath);
        } else {
            params.put("charset", Constants.CHARSET_UTF_8);
            // sm2
            sign = YsPaySignUtils.sign(params, pwd, filePath);
        }
        /** 3、对数据进行加签，并存入请求数据*/
        log.info("【支付签名sign】：" + sign);
        return sign;
    }

    public static void checkSign(String type, String responseMethod, String result, String PublicKeyFilePath) throws Exception {
        if (!Arrays.asList("RSA", "SM").contains(type)) throw new Exception("sign_type 类型错误 只能 RSA SM");
        boolean flag = false;
        if (Constants.YSF_SIGN_TYPE_RSA.equals(type)) {
            JSONObject resultJson = JSONObject.parseObject(result, Feature.OrderedField);
            //加签内容
            String content = resultJson.getString(responseMethod);
            //加签值
            String sinaValue = resultJson.getString("sign");
            flag = YsOnlineSignUtils.rsaCheckContent(content, sinaValue, Constants.CHARSET_GBK, PublicKeyFilePath);

        } else {
            flag = YsPaySignUtils.resultVerify(result, responseMethod, PublicKeyFilePath);
        }

        if (!flag) {
            throw new Exception("check sign error");
        }
    }


}
